using System;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.Scripting;

public class SGDownloadHandlerWXAssetBundle : DownloadHandlerScript
{
    private string m_Url;
    private uint m_Crc;
    private AssetBundle m_AssetBundle;
    private byte[] m_Data;
    private int m_Length;
    private uint m_Offset;
    public bool isDone;

    public SGDownloadHandlerWXAssetBundle(string uri, uint crc, uint offset)
    {
        m_Url = uri;
        m_Crc = crc;
        m_Offset = offset;
    }

    [Preserve]
    public AssetBundle assetBundle
    {
        get
        {
            if (m_AssetBundle == null)
            {
                // if (WXAssetBundle.wxfs_ready)
                // {
                //     if (m_Length != 0)
                //     {
                //         return null;
                //     }
                //     // TODO :  确认下，这里有可能不能用 m_offset
                //     m_AssetBundle = AssetBundle.LoadFromFile(m_Url, m_Crc, m_Offset);
                //     if (m_AssetBundle != null)
                //     {
                //         WXAssetBundle.bundle2path.Add(m_AssetBundle, m_Url);
                //     }
                // }
                // else
                {
                    m_AssetBundle = AssetBundle.LoadFromMemory(m_Data);
                }
            }
            return m_AssetBundle;
        }
    }
    
    [Preserve]
    protected override byte[] GetData() => this.m_Data;
    
    [Preserve]
    protected override bool ReceiveData(byte[] data, int dataLength)
    {
        if (data == null || dataLength < 1)
            return false;

        var length = (int)(m_Length - m_Offset + dataLength);
        if (length > 0)
        {
            Array.Resize<byte>(ref m_Data, length);
            var offset = m_Offset > m_Length ? m_Offset - m_Length : 0;
            var idx = m_Offset > m_Length ? 0 : m_Length - m_Offset;
            Array.Copy(data, offset, m_Data, idx, dataLength - offset);
        }
        m_Length += dataLength;
        return true;
    }

    [Preserve]
    protected override void CompleteContent() => isDone = true;
}